<?php

namespace App\Http\Controllers;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
    private $statusData = [
        0 => '未付款', 1 => '已付款', 2 => '已取消',
    ];


    public function lists()
    {
        return view('order.lists');
    }

    public function doLists(Request $request)
    {
        $key = $request->input('key', '');
        $pageSize = $request->input('limit', '10');
        $where = [];
        $orwhere = [];
        if (!empty($key)) {
            $where[] = ['user_name', 'like', '%' . $key . '%'];
            $orwhere[] = ['user_email', 'like', '%' . $key . '%'];
        }
        //查询账号
        $count = DB::table('order')->where($where)->orWhere($orwhere)->count();
        $order = (array)DB::table('order')->where($where)->orWhere($orwhere)->paginate($pageSize)->items();
        foreach ($order as &$value) {
            $value = (array)$value;
            $value['status_str'] = $this->statusData[$value['status']];
        }
        unset($value);
        return $this->success($order, '', ['count' => $count]);
    }

    public function edit(Request $request)
    {
        $id = $request->input('id', '0');
        $order = (array)DB::table('order')
            ->where(['id' => $id])
            ->first();
        $order['status_str'] = $this->statusData[$order['status']];
        return view('order.edit', [
            'order' => $order
        ]);
    }

    public function doEdit(Request $request)
    {
        $id = $request->input('id', '0');
        $goodsEdit = (array)DB::table('order_product')
            ->where(['order_id' => $id])
            ->get()
            ->map(function ($modelValue) {
                return (array)$modelValue;
            })
            ->toArray();
        return $this->success($goodsEdit);
    }
    public function del(Request $request)
    {
        try {
            $ids = $request->input('ids', '0');
            if (empty($ids)) throw new \Exception("删除失败");
            if (!is_array($ids)) {
                $ids = [$ids];
            }
            $res = DB::table('order')->whereIn('id', $ids)->delete();
            $res = DB::table('order_product')->whereIn('order_id', $ids)->delete();
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success();
    }

}
